package cn.gzsf.springboot10.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@RestController
public class UploadController {

    @RequestMapping("/upload")
    public String upload(MultipartFile picFile) throws IOException {
        //图片的原始文件名
        String filename = picFile.getOriginalFilename();
        System.out.println(filename);//logo.png
        //filename.lastIndexOf("."):从filename字符串最后面往前找第一个”.“的下标
        //filename.substring(index):从下标index处，开始截取到末尾
        String suffix = filename.substring(filename.lastIndexOf("."));
        //System.out.println("suffix="+suffix);
        //得到唯一的名称，UUID.randomUUID(获得一个字符串类型的唯一标识符)
        filename = UUID.randomUUID()+suffix;
        System.out.println(filename);
        //准备上传文件夹路径
        String dirPath = "d:/files";
        //准备一个和日期向的路径  SimpleDateFormat:将日期对象格式化为指定的字符串
        SimpleDateFormat sdf = new SimpleDateFormat("/yyyy/MM/dd/");
        String datePath = sdf.format(new Date());
        //d:/files/2025/06/03
        File dirFile = new File(dirPath + datePath);
        //如不存在，则创建
        if(!dirFile.exists()){
            dirFile.mkdirs();
        }
        //把接收到的文件保存到上面文件夹   d:/files/2025/06/03/xxxx.jpg
        picFile.transferTo(new File(dirPath+datePath+filename));

        return datePath+filename;
    }

    @RequestMapping("/remove")
    public void remove(String url){
        File file = new File("d:/files" + url);
        file.delete();
    }

}
